﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPI_Demo.Filter;
using WebAPI_Demo.Models;
using WebAPI_Demo.Models.Database;
using WebAPI_Demo.Service;

namespace WebAPI_Demo.Controllers
{
    /// <summary>
    /// 商品控制器
    /// </summary>

    //控制器的路由：api/控制器名字(Good)/方法名
    [Route("api/[controller]/[action]")]
    //有Attribute类才可以这使用授权(权限)过滤器
    [AuthorizeFilter]
    //API控制器的标识
    [ApiController]
    public class GoodController : ControllerBase
    {
        //定义数据库上下文
        private readonly Store_2022Context _db;
        //定义数据服务类      类型           变量名    (_开头代表全局)
        private readonly IDataServices _dataServices;
        private readonly ISingletonService _singletonService;
        private readonly ITransientService _transientService;
        private readonly IScopedService _scopedService;

        /// <summary>
        /// 构造方法 构造注入
        /// 把数据库上下文初始化
        /// </summary>
        public GoodController(Store_2022Context db, IDataServices dataServices, ISingletonService singletonService, ITransientService transientService, IScopedService scopedService)
        {
            _db = db;
            _dataServices = dataServices;
            _singletonService = singletonService;
            _transientService = transientService;
            _scopedService = scopedService;
        }

        /// <summary>
        /// 新增产品
        /// </summary>
        /// <param name="good"></param>
        /// <returns></returns>
        //定义支持的请求方式
        [HttpPost]
        //public：访问权限   string：返回参数数据类型   AddGood：方法名   (Good：请求参数的数据类型 good：变量)
        //控制器的路由url(也叫接口的地址)：api/Good/AddGood
        public string AddGood(Good good)
        {
            //后端做的事情
            //业务逻辑编写 添加商品
            //把商品添加到数据库

            //数据库上下文.操作的表名.操作的方法(参数)
            _db.Goods.Add(good);
            //row：接收影响行数   _db.SaveChanges()：数据库的执行
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "新增商品1成功";
            }
            else
            {
                return "新增商品1失败";
            }

        }


        /// <summary>
        /// 新增产品2 自定请求类
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public string AddGood2(AddGood2 request)
        {
            //手动转换类 把请求类 转换 成 数据库模型类
            var good = new Good()
            {
                Name = request.Name,
                CateId = request.CateId,
                Cover = request.Cover,
                CreateTime = DateTime.Now,
                Price = request.Price,
                Stock = request.Stock,
            };
            //数据库上下.操作的表名.操作的方法(参数)
            _db.Goods.Add(good);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "新增商品2成功";
            }
            else
            {
                return "新增商品2失败";
            }
        }


        /// <summary>
        /// 新增商品3
        /// </summary>
        /// <param name="name"></param>
        /// <param name="cateId"></param>
        /// <param name="cover"></param>
        /// <param name="price"></param>
        /// <param name="stock"></param>
        /// <returns></returns>
        [HttpPost]
        public string AddGood3(string name, int cateId, string cover, decimal price, int stock)
        {
            _db.Goods.Add(new Good()
            {
                Name = name,
                CateId = cateId,
                Cover = cover,
                CreateTime = DateTime.Now,
                Price = price,
                Stock = stock,
            });
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "新增商品3成功";
            }
            else
            {
                return "新增商品3失败";
            }
        }

        /// <summary>
        /// 新增商品4
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public string AddGood4(AddGood2 request)
        {
            //验证模型 !false = true
            //if (!ModelState.IsValid)
            //{
            //    return "数据错误";
            //}
            //手动转换类 把请求类 转换 成 数据库模型类
            var good = new Good()
            {
                Name = request.Name,
                CateId = request.CateId,
                Cover = request.Cover,
                CreateTime = DateTime.Now,
                Price = request.Price,
                Stock = request.Stock,
            };
            //数据库上下.操作的表名.操作的方法(参数)
            _db.Goods.Add(good);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "新增商品4成功";
            }
            else
            {
                return "新增商品4失败";
            }
        }

        //重点 怎么写一个接口
        //有什么

        //1、支持的请求方式
        //[HttpGet]  查询接口
        //[HttpPost] 增删改

        //2public 访问权限

        //3方法的返回类型string  根据需求、返回值决定类型是什么

        //4请求方法名 决定请求的路径

        //5请求参数 不同的类型

        //6业务逻辑 根据接口需求 //登录 注册

        //7返回参数 根据接口需求 return 


        /// <summary>
        /// 更新产品信息
        /// </summary>
        /// <param name="good"></param>
        /// <returns></returns>
        [HttpPost]
        public string UpdateGood(UpdateGood good)
        {
            var goods = _db.Goods.FirstOrDefault(x => x.Id == good.Id);
            if (goods == null)
            {
                return "请检查所更改的商品id";
            }
            //把前端传过来数据赋值
            goods.Name = good.Name;
            goods.CateId = good.CateId;
            goods.Cover = good.Cover;
            goods.Price = good.Price;
            goods.Stock = good.Stock;
            goods.UpdateTime = DateTime.Now;
            //数据库更新操作
            _db.Goods.Update(goods);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "更新成功";
            }
            else
            {
                return "更新失败";
            }

        }


        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public string DeleteGood(int id)
        {
            //删除哪个商品 查询指定商品
            var good = _db.Goods.FirstOrDefault(x => x.Id == id);
            if (good == null)
            {
                return "查不到该商品哦";
            }
            _db.Remove(good);
            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "删除商品成功";
            }
            else
            {
                return "删除商品失败";
            }
        }


        /// <summary>
        /// 根据商品ID或者关键词进行查询商品
        /// </summary>
        /// <param name="id">编号</param>
        /// <param name="KeyWord"></param>
        /// <returns></returns>
        [HttpGet]
        public List<Good> SelectGood(int id, string KeyWord)
        {
            //获取商品操作
            var goodList = _db.Goods.AsQueryable();
            //如果查询的商品Id>0 
            if (id > 0)
            {
                goodList = goodList.Where(x => x.Id == id);
            }
            //如果查询的关键字不为空
            if (!string.IsNullOrEmpty(KeyWord))
            {
                goodList = goodList.Where(x => x.Name.Contains(KeyWord));
            }
            return goodList.ToList();
        }

        /// <summary>
        /// 根据分类ID或者关键词进行查询全部商品
        /// </summary>
        /// <param name="cateid"></param>
        /// <param name="KeyWord"></param>
        /// <returns></returns>
        [HttpGet]
        //使用自定义资源过滤器
        [CustomerResourceFilter]
        public List<GoodModel> GetGoodAllList(int cateid, string KeyWord)
        {
            //获取商品操作
            var goodList = _db.Goods.AsQueryable();
            //如果查询的分类Id>0 
            if (cateid > 0)
            {
                goodList = goodList.Where(x => x.CateId == cateid);
            }
            //如果查询的关键字不为空
            if (!string.IsNullOrEmpty(KeyWord))
            {
                goodList = goodList.Where(x => x.Name.Contains(KeyWord));
            }

            //开始连表            连接表           主表外键      连接表的主键    把两个表的字段结合起来 新建一个模型
            var list = goodList.Join(_db.Categories, x => x.CateId, y => y.Id, (x, y) => new GoodModel
            {
                Name = x.Name,
                CateId = x.CateId,
                CategoryName = y.CateName,
                Cover = x.Cover,
                Id = x.Id,
                Price = x.Price,
                Stock = x.Stock
            })
                //执行SQL查询
                .ToList();
            return list;
        }


        /// <summary>
        /// 
        /// </summary>
        [HttpPost]
        public void Test()
        {
            //主动去实例化 这个类 a
            var data = new DataServices();
            //把实例化的过程 交给第三方（程序算法）去做 自己不实例化 再去IOC容器去获取这个对象去使用  IOC\

            data.GetData();
        }

        [HttpPost]
        public string GetData([FromServices]IDataServices dataService2)
        {
            //控制器获取的服务
            _dataServices.GetData();

            //接口方法获取服务
            dataService2.GetData();

            dataService2.GetHashCode();
            //GetHashCode获取对象的HashCode判断HashCode是否一致 判断我们的对象是不是同一个对象

            return "1的hashcode=" + _dataServices.GetHashCode() + "  2的hashcode=" + dataService2.GetHashCode();
        }

        /// <summary>
        /// 启动 应用程序后 无论怎么获取 都是那个对象 
        /// </summary>
        /// <param name="singletonService"></param>
        /// <returns></returns>
        [HttpPost]
        public string Singleton([FromServices] ISingletonService singletonService)
        {
            return "1的hashcode=" + _singletonService.GetHashCode() + "  2的hashcode=" + singletonService.GetHashCode();
        }

        /// <summary>
        /// 无论怎么获取 都是新的对象 
        /// </summary>
        /// <param name="transientService"></param>
        /// <returns></returns>
        [HttpPost]
        public string Transient([FromServices] ITransientService transientService)
        {
            return "1的hashcode=" + _transientService.GetHashCode() + "  2的hashcode=" + transientService.GetHashCode();
        }

        /// <summary>
        /// 在一次请求 无论获取多少次 都是同一个对象
        /// </summary>
        /// <param name="scopedService"></param>
        /// <returns></returns>
        [HttpPost]
        public string Scoped([FromServices] IScopedService scopedService)
        {
            return "1的hashcode=" + _scopedService.GetHashCode() + "  2的hashcode=" + scopedService.GetHashCode();
        }
    }
}
